﻿using System.Threading.Tasks;
using WenAntdUI.Helps;

namespace WenAntdUI.Services
{
    public class IdentityService(UserService userService) : INotifyPropertyChanged
    {
        public SysUser? SysUser { get; private set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string? UserName => SysUser?.UserName;

        /// <summary>
        /// 说明
        /// </summary>
        public string? Description => SysUser?.Description;


        private Image? _image;
        public Image? Image
        {
            get
            {
                if (_image != null)
                {
                    return _image;
                }
                else if (SysUser?.Icon != null)
                {
                    return _image = ImageHelp.GetImage(SysUser.Icon);
                }
                return null;
            }
            set
            {
                if (_image != value)
                {
                    var bitString = ImageHelp.ToBase64String(value);
                    _image = value;
                    if (SysUser != null)
                    {
                        SysUser.Icon = bitString;
                    }
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Image)));
                }
            }
        }

        /// <summary>
        /// 显示名称
        /// </summary>
        public string? DisplayName
        {
            get => SysUser?.DisplayName;
            set
            {
                if (SysUser != null && SysUser.DisplayName != value)
                {
                    SysUser.DisplayName = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DisplayName)));
                }
            }
        }

        /// <summary>
        /// 用户密码
        /// </summary>
        public string? Password { get; private set; }
        /// <summary>
        /// 设置用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void SetUserInfo(string username, string password)
        {
            Password = password;
            SysUser = userService.GetUserByUserName(username);
        }

        private string? _token;
        private DateTime _tokenExpireTime = DateTime.MinValue;

        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 获取用户Token
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetUserTokenAsync()
        {
            if (_tokenExpireTime < DateTime.Now)
            {
                _token = await new AuthClient().GetTokenAsync(UserName, Password);
                _tokenExpireTime = DateTime.Now.AddMinutes(30);
            }
            return _token;
        }
    }
}
